package com.gm.wholesale.module.report.ui.tab;

import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.github.gzuliyujiang.calendarpicker.OnRangeDatePickListener;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.timePickerView.TimePickerViewUtils;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.module.report.bean.SaleReportBean;
import com.gm.wholesale.module.report.model.ReportModel;
import com.gm.wholesale.module.report.view.BarChartUtil;
import com.gm.wholesale.module.report.view.ReportTabTimeView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SaleReportFragment extends BaseFragment implements View.OnClickListener {
    private ReportTabTimeView todayTv;
    private ReportTabTimeView weekTv;
    private ReportTabTimeView monthTv;
    private TextView choiceTimeTv;
    private TextView salePriceTv;
    private TextView saleNumberTv;
    private TextView reviceMoneyTv;
    private TextView preferentialMoneyTv;

    private String mTimeBegin;
    private String mTimeEnd;

    private String mChoiceTime;

    private BarChart mBarChart;

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_sale_report, parent);
        initView(view);
        getData();
    }

    private void initView(View view) {
        todayTv = view.findViewById(R.id.todayTv);
        weekTv = view.findViewById(R.id.weekTv);
        mBarChart = view.findViewById(R.id.barChart);
        BarChartUtil.initBarChart(mBarChart);
        monthTv = view.findViewById(R.id.monthTv);
        choiceTimeTv = view.findViewById(R.id.choiceTimeTv);
        salePriceTv = view.findViewById(R.id.salePriceTv);
        saleNumberTv = view.findViewById(R.id.saleNumberTv);
        reviceMoneyTv = view.findViewById(R.id.reviceMoneyTv);
        preferentialMoneyTv = view.findViewById(R.id.preferentialMoneyTv);
        todayTv.showCheck();
        todayTv.setOnClickListener(this);
        weekTv.setOnClickListener(this);
        monthTv.setOnClickListener(this);
        choiceTimeTv.setOnClickListener(this);
        mTimeBegin = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
        mChoiceTime = mTimeBegin + " 至 " + mTimeBegin;
        mTimeEnd = mTimeBegin;
        setChoiceTime();
    }

    private void setChoiceTime() {
        choiceTimeTv.setText(mChoiceTime);
    }

    private void getData() {
        ArrayMap<String, Object> queryData = new ArrayMap<>();

        queryData.put("dateBegin", mTimeBegin + " 00:00:00");
        queryData.put("dateEnd", mTimeEnd + " 23:59:59");
        ReportModel.getSaleReport(null, queryData, new BaseHttpObserver<DataResp<SaleReportBean>>() {
            @Override
            protected void handleResultOkResp(DataResp<SaleReportBean> resp) {
                showView(resp.getData());
                showBarChart(resp.getData());
            }
        });
    }

    private void showView(SaleReportBean saleReportBean) {
        salePriceTv.setText(saleReportBean.getOnsiteSalesAmount());
        saleNumberTv.setText(saleReportBean.getOnsiteOrderCount() + "");
        reviceMoneyTv.setText(saleReportBean.getPaidAmount());
        preferentialMoneyTv.setText(saleReportBean.getDiscountAmount());
    }

    private void showBarChart(SaleReportBean saleReportBean) {


        ArrayList<BarEntry> yValues = new ArrayList<>();

        List<SaleReportBean.TrendBean> datas = saleReportBean.getTrend();
        if (datas == null) return;
        int pos = 0;
        for (SaleReportBean.TrendBean trendBean : datas) {
            yValues.add(new BarEntry(pos, Float.parseFloat(trendBean.getValue())));
            pos++;
        }
        // y 轴数据集
        BarDataSet barDataSet = new BarDataSet(yValues, "");
        BarData mBarData = new BarData(barDataSet);
        barDataSet.setDrawValues(false);
        mBarChart.setData(mBarData);
        mBarChart.setFitBars(true);
        barDataSet.setColors(getResources().getColor(R.color.color_06C160));
        mBarChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                try {
                    int index = Math.round(value);
                    String data = datas.get(index).getDate();
                    data = data.substring(data.indexOf("-") + 1, data.length());
                    return data;
                } catch (Exception e) {
                    return "";
                }
            }
        });
        mBarChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                LogUtil.d("onValueSelectedonValueSelected: ");
                try {
                    SaleReportBean.TrendBean trendBean = datas.get((int) e.getX());
                    String data = trendBean.getDate() + "\n" + trendBean.getValue() + "元";
                    ToastUtil.showToast(data);
                } catch (Exception exception) {

                }

            }

            @Override
            public void onNothingSelected() {

            }
        });

        mBarData.notifyDataChanged();
        mBarChart.invalidate();

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.todayTv) {
            mTimeBegin = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
            mChoiceTime = mTimeBegin + " 至 " + mTimeBegin;
            setChoiceTime();
            todayTv.showCheck();
            weekTv.showUnCheck();
            monthTv.showUnCheck();
            getData();
        } else if (view.getId() == R.id.weekTv) {
            mTimeBegin = DateTimeUtils.getWeekStart();
            mTimeEnd = DateTimeUtils.getWeekEnd();
            mChoiceTime = mTimeBegin + " 至 " + mTimeEnd;
            todayTv.showUnCheck();
            weekTv.showCheck();
            monthTv.showUnCheck();
            setChoiceTime();
            getData();
        } else if (view.getId() == R.id.monthTv) {
            mTimeBegin = DateTimeUtils.getMonthStart();
            mTimeEnd = DateTimeUtils.getMonthEnd();
            mChoiceTime = mTimeBegin + " 至 " + mTimeEnd;
            todayTv.showUnCheck();
            weekTv.showUnCheck();
            monthTv.showCheck();
            setChoiceTime();
            getData();
        } else if (view.getId() == R.id.choiceTimeTv) {
            long startTime = DateTimeUtils.getTimeStringToLong(mTimeBegin + " 00:00:01", DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
            long endTime = DateTimeUtils.getTimeStringToLong(mTimeEnd + " 23:59:59", DateTimeUtils.LONG_DATETIME_FORMAT_STRING);
            CalendarPicker calendarPicker = TimePickerViewUtils.showTimePicker(getActivity(), startTime, endTime);
            calendarPicker.setOnRangeDatePickListener(new OnRangeDatePickListener() {
                @Override
                public void onRangeDatePicked(@NonNull Date startDate, @NonNull Date endDate) {
                    setViewUnCheck(todayTv);
                    setViewUnCheck(weekTv);
                    setViewUnCheck(monthTv);
                    mTimeBegin = DateTimeUtils.formatDateTime(startDate, DateTimeUtils.YMD);
                    mTimeEnd = DateTimeUtils.formatDateTime(endDate, DateTimeUtils.YMD);
                    mChoiceTime = mTimeBegin + " 至 " + mTimeEnd;
                    setChoiceTime();
                    getData();
                }
            });
        }


    }


    private void setViewUnCheck(ReportTabTimeView view) {
        view.showUnCheck();
    }
}
